package cn.jg.service.sys.impl;

import cn.jg.framework.auth.session.SessionManager;
import cn.jg.model.sys.User;
import cn.jg.dao.repository.sys.command.UserCommandMapper;
import cn.jg.dao.repository.sys.query.UserQueryMapper;
import cn.jg.service.sys.UserService;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by admin on 2023/06/06.
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserQueryMapper userQueryMapper;
    private final UserCommandMapper userCommandMapper;

    @Override
    public Optional<User> findById(@NonNull final Integer id) {
        Optional<User> userPossible = userQueryMapper.findById(id);
        return userPossible;
    }

    @Override
    public boolean exists(@NonNull final Integer id) {
        Optional<User> userPossible = userQueryMapper.findById(id);
        return userPossible.isPresent();
    }

    @Override
    public List<User> findAll(final Integer pageNum, final Integer pageSize) {
        if (Objects.nonNull(pageNum) && Objects.nonNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<User> userList = userQueryMapper.findAll();
        return userList;
    }

    @Override
    public User save(@NonNull final User user) {
        SessionManager.packingCreateInfo(user);
        userCommandMapper.save(user);
        return user;
    }

    @Override
    public User update(@NonNull final User user) {
        SessionManager.packingUpdateInfo(user);
        userCommandMapper.update(user);
        return user;
    }

    @Override
    public void delete(Integer id) {
        userCommandMapper.deleteById(id);
    }
}
